package repository

import (
	"RocFamilySystem/models"
	"fmt"
	"gorm.io/gorm"
	"time"
)

type SysUserRepository struct {
	Db *gorm.DB
}

func init() {
	registerContainer["SysUserRepository"] = &SysUserRepository{}
}

func (r *SysUserRepository) SetDB(db *gorm.DB) {
	r.Db = db
}

// InsertSysUser 添加系统系统用户
func (r *SysUserRepository) InsertSysUser(sysUser *models.SysUser) {

	//开启事务
	db := r.Db.Begin()
	defer handleTransactional(db)
	now := models.LocalTime(time.Now())
	sysUser.CreateTime = &now
	err := db.Save(sysUser).Error
	handleRepositoryErr(err, "添加系统用户失败")
}

// DeleteSysUser 删除系统系统用户
func (r *SysUserRepository) DeleteSysUser(sysUserId int) {
	db := r.Db.Begin()
	defer handleTransactional(db)

	err := db.Delete(&models.SysUser{Id: &sysUserId}).Error
	handleRepositoryErr(err, "添加系统用户失败")
}

// DeleteSysUserBatch 批量删除系统用户
func (r *SysUserRepository) DeleteSysUserBatch(ids []string) {
	db := r.Db.Begin()
	defer handleTransactional(db)
	err := db.Where("id in (?)", ids).Delete(models.SysUser{}).Error
	handleRepositoryErr(err, "删除系统缓存失败！")
}

// UpdateSysUser 修改系统系统用户
func (r *SysUserRepository) UpdateSysUser(sysUser *models.SysUser) {
	now := models.LocalTime(time.Now())
	sysUser.UpdateTime = &now

	err := r.Db.Model(sysUser).Omit("id", "create_time").Updates(sysUser).Error
	handleRepositoryErr(err, "修改系统用户失败")
}

// SelectSysUser 查询系统系统用户
func (r *SysUserRepository) SelectSysUser(sysUser *models.SysUser, pageNum, pageSize int) ([]models.SysUser, int) {
	var (
		list  []models.SysUser
		total int64
	)
	db := r.Db.Model(&models.SysUser{})

	if sysUser != nil {
		if sysUser.Username != nil {
			db = db.Where("username like ?", fmt.Sprintf("%%%s%%", *sysUser.Username))
		}
		if sysUser != nil {
			if sysUser.NickName != nil {
				db = db.Where("nick_name like ?", fmt.Sprintf("%%%s%%", *sysUser.NickName))
			}
		}
	}
	//获取总数
	db.Count(&total)

	//获取列表
	db.Offset(pageSize * pageNum).Limit(pageSize)
	db.Find(&list)

	return list, int(total)
}

// SelectSysUserById 查询系统用户通过ID
func (r *SysUserRepository) SelectSysUserById(id int) models.SysUser {
	var sysUser models.SysUser
	err := r.Db.First(&sysUser, "id = ?", id).Error
	if err != nil {
		handleRepositoryErr(err, "查询失败")
	}
	return sysUser
}

// SelectSysUserByUsername 通过用户名查找用户
func (r *SysUserRepository) SelectSysUserByUsername(username string) models.SysUser {
	var sysUser models.SysUser
	r.Db.Where("username = ?", username).Take(&sysUser)
	return sysUser
}
